﻿using System;

namespace TestingConcurrencyBenchmark.Helpers
{
    /// <summary>
    /// A non-threadsafe ActionQueue for usage with the producer consumer problem
    /// This ActionQueue contains a static array of Action and an index pointing to the latest entry
    /// </summary>
    public class ActionQueue
    {
        /// <summary>
        /// The internal static array of Action
        /// </summary>
        private readonly Action[] _actions = new Action[100];

        /// <summary>
        /// A volatile counter
        /// </summary>
        private volatile int _count;
        public int Count
        {
            get { return _count; }
            private set { _count = value; }
        }

        /// <summary>
        /// Enqueues an action on the internal static array
        ///     | new.Peek() == action
        ///     | new.Count == this.Count + 1
        /// </summary>
        /// <param name="action">The action to enqueue</param>
        public void Enqueue(Action action)
        {
            _actions[Count++] = action;
        }

        /// <summary>
        /// Dequeues an action from the internal static array
        ///     | new.Peek() == this._actions[Count - 2]
        ///     | new.Count == this.Count - 1
        /// </summary>
        /// <returns>the last action on the internal array</returns>
        public Action Dequeue()
        {
            return _actions[--Count];
        }

        /// <summary>
        /// Checks which action was last added without removing it
        /// </summary>
        /// <returns>the last action enqueued</returns>
        public Action Peek()
        {
            return _actions[Count-1];
        }
    }
}